package net.xo68.destiny.manager.eventHandle;

import com.lmax.disruptor.EventHandler;
import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.node.NodeRegistry;
import net.xo68.destiny.core.discovery.NodeDiscoveryClient;
import net.xo68.destiny.core.eventbus.MessageEvent;
import net.xo68.destiny.core.util.TimeUtils;
import net.xo68.destiny.manager.entity.NodeMonitor;
import net.xo68.destiny.manager.service.NodeHeartbeatService;
import net.xo68.destiny.manager.service.NodeMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 工作节点注册
 */
@Component
@Slf4j
public class NodeRegistryEventHandle  implements EventHandler<MessageEvent> {

    @Autowired
    private NodeHeartbeatService nodeHeartbeatService;
    @Autowired
    private NodeDiscoveryClient nodeDiscoveryClient;
    @Autowired
    private NodeMonitorService nodeMonitorService;

    @Override
    public void onEvent(MessageEvent messageEvent, long l, boolean b) throws Exception {
        if(messageEvent.getBody()!=null){
            if(messageEvent.getBody() instanceof NodeRegistry){
                NodeRegistry nodeRegistry=messageEvent.mesageBody(NodeRegistry.class);
                nodeRegistry.setLastTime(TimeUtils.nowDate());
                //log.debug("Registry node:{}",nodeRegistry);
                nodeDiscoveryClient.addWorkNode(nodeRegistry);
                nodeHeartbeatService.UpdateHeartbeat(nodeRegistry);

                NodeMonitor nodeMonitor=new NodeMonitor();
                nodeMonitor.setNodeHost(nodeRegistry.getNodeHost());
                nodeMonitor.setNodeTypeName(nodeRegistry.getNodeType().name());
                nodeMonitor.setWorkGroupName(nodeRegistry.getWorkGroup());
                nodeMonitor.setCpuUsage(nodeRegistry.getCpuUsage());
                nodeMonitor.setMemoryUsage(nodeRegistry.getMemoryUsage());
                nodeMonitor.setLoadAverage(nodeRegistry.getLoadAverage());
                nodeMonitor.setRegTime(nodeRegistry.getLastTime());
                nodeMonitorService.insert(nodeMonitor);

            }else {
                log.error("事件消息体结构异常,event: {}",messageEvent);
            }
        }else {
            log.error("事件消息体为空");
        }
    }
}
